<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>web摄像头录制并上传</title>
</head>
<body>
    <div class="left">
        <!-- <video id="recording" width="160" height="120" controls style="float: right;"></video> -->
        <p>
            <button id="startButton2" class="button">手动开始</button>
            <button id="stopButton" class="button">手动结束</button>
            <a id="downloadButton" class="button" style="display:none;">下载</a>
        </p>
        <p>
            <button id="startButton" class="button">批量开始</button>  每隔5秒录制一次，连续录制5次，并上传到OSS
        </p>
       
        
          
        <h2>摄像头</h2>
        <div class="video"><video id="preview" width="400" height="auto" autoplay muted></video></div>
      </div>
      
      
      <div class="right">
        <h2>录制结果</h2>
        <div style="visibility: hidden;height:1px">
            <video id="record-demo" width="160" height="120" controls></video>
        </div>
        <div class="video" id="recordingWrap">

        </div>
        <h2>上传结果</h2>
        <div class="video" id="recordingWebWrap">

        </div>
        <div>视频链接</div>
        <p id="videoUrl"></p>
      </div>
      <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script  type="module">
        let preview = document.getElementById("preview");
        // let recording = document.getElementById("recording");
        let startButton = document.getElementById("startButton");
        let startButton2 = document.getElementById("startButton2");
        let stopButton = document.getElementById("stopButton");
        let downloadButton = document.getElementById("downloadButton");
        let videoUrl = document.getElementById("videoUrl");
        let dataChunks = [];
        let recorder;
        let arr=[1,2,3,4,5];
        let res=[];

        // 开始录制
        function startRecording(stream, lengthInMS) {
            recorder = new MediaRecorder(stream);

            recorder.ondataavailable = (event) => {
                let data = event.data;
                dataChunks.push(data);
            };
            recorder.start(1000);
            console.log(recorder.state + " start to recording .....");
        }
        function start(code){
            console.log('start==',code)
                // get the stream
                navigator.mediaDevices.getUserMedia({
                    audio: true,
                    video: true,
                })
                .then((stream) => {
                // set the stream to left video
                preview.srcObject = stream;
                // set the stream to <a> for download
                
                // captureStream: which is streaming a real-time capture of the content being rendered in the media element. 
                // A MediaStream object  which can be used as a source for audio or video data by other media
                preview.captureStream = preview.captureStream || preview.mozCaptureStream;
                dataChunks=[];
                startRecording(preview.captureStream());
                })
                .catch((err) => {
                    console.log("recording error: ", err);
                });
        }
        function stop(code){
            console.log('stop==',code)
            // close the recording
            preview.srcObject.getTracks().forEach((track) => track.stop());
            recorder.stop();

            // Play recorded video
            let recordedBlob = new Blob(dataChunks, { type: "video/webm" });
            let src = URL.createObjectURL(recordedBlob);
            // recording.src =src;

            // Save download video， click the download button， you can download it
            downloadButton.href = src;
            downloadButton.download = "RecordedVideo.webm";
            downloadButton.style.display = "inline";

            res.push(src)

            //复制dom
            var node=document.getElementById("record-demo").cloneNode(true);
            node.src = src;
            document.getElementById("recordingWrap").appendChild(node);

            //上传
            uploadFile(recordedBlob);
        }
        function uploadFile(blob){
            var file = new File([blob], "media.webm");
            var formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            console.log("# 准备上传, fileName="+file.name +", size="+ parseInt(file.size/1024)+" KB");
            axios({
                method: "post",
                url: "https://1246864230931382.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/test.LATEST/upload/",
                headers: {
                    Accept: "*/*",
                    "Content-Type": "multipart/form-data",
                },
                data: formData,
            }).then((res) => {
                console.log(res.data);
                let src = res.data.data;
                var node=document.getElementById("record-demo").cloneNode(true);
                node.src = src;
                document.getElementById("recordingWebWrap").appendChild(node);
                videoUrl.innerText=videoUrl.innerText+src+'\n'
            }).catch(err=>console.log(err))
             
        }


        stopButton.addEventListener("click", () => {
            stop();
        });

        startButton.addEventListener("click", () => {
            ctlList()
        });
        startButton2.addEventListener("click", () => {
            start();
        });
        async function ctlList(){
            for (let index = 0; index < arr.length; index++) {
                const code = arr[index];
                start(code);
                await sleep(5000);
                stop(code);
                
                await sleep(1000)
            }
            console.log(res);
        }

        async function sleep(time) {
            return new Promise((resolve) => {
                setInterval(() => {
                    resolve();
                }, time);
            });
        }
    </script>
</body>
</html>